package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.SupplierContactUserEntity;
import com.xbongbong.saas.domain.entity.ext.SupplierContactEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowSupplierContactStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        String corpid = workflowTransferPOJO.getCorpid();
        Long backupDataId = workflowTransferPOJO.getBackupDataId();
        Long dataId = workflowTransferPOJO.getData().getId();
        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
        if (Objects.nonNull(workflowBackupDataEntity)) {
            JSONObject data = workflowBackupDataEntity.getData();

            replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

            SupplierContactEntityExt supplierContactEntityExt = new SupplierContactEntityExt();
            supplierContactEntityExt.setId(dataId);
            supplierContactEntityExt.setCorpid(corpid);
            supplierContactEntityExt.setData(data);
            supplierContactEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
            supplierContactEntityExt.setOwnerId(getOwnerId(data));
            supplierContactEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));

            List<SupplierContactUserEntity> userEntities = JSON.parseArray(data.getString(StringConstant.USER_TEAM), SupplierContactUserEntity.class);

            FormDataUtil.removeSystemData(data);
            data.remove(StringConstant.USER_TEAM);
            if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                supplierContactEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
            }
            supplierContactModel.update(supplierContactEntityExt);
            // 回退被删掉的子表单
            updateBackSubForm(supplierContactEntityExt, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
            //回退被删掉的富文本
            updateBackRichText(taskId, workflowTransferPOJO);
            // 团队处理
            saveUserTeam(userEntities, corpid, supplierContactEntityExt.getId());
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            SupplierContactEntityExt supplierContactEntityExt = new SupplierContactEntityExt();
            supplierContactEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                supplierContactEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                supplierContactEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            supplierContactEntityExt.setCorpid(corpid);
            supplierContactEntityExt.setUpdateTime(DateTimeUtil.getInt());
            supplierContactModel.update(supplierContactEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            List<SupplierContactUserEntity> userEntities = supplierContactUserModel.getBySupplierId(corpid, dataId, DelEnum.NORMAL.getDel());
            if (CollectionUtils.isNotEmpty(userEntities)) {
                supplierContactUserModel.deleteBatchUser(userEntities, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowSupplierContactStrategy.approvalFailed error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveUserTeam(List<SupplierContactUserEntity> supplierContactUserEntities, String corpid, Long id) throws XbbException {
        try {
            List<Long> ids = new ArrayList<>();
            supplierContactUserEntities.forEach(v -> ids.add(v.getId()));

            List<SupplierContactUserEntity> userEntities = supplierContactUserModel.getBySupplierId(corpid, id);
            List<SupplierContactUserEntity> delUserEntity = userEntities.stream().filter(v -> !ids.contains(v.getId())).collect(Collectors.toList());

            supplierContactUserModel.deleteBatchUser(delUserEntity, corpid, DelEnum.DELETE.getDel());

            supplierContactUserModel.updateBatch(supplierContactUserEntities, corpid);


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowSupplierContactStrategy.saveUserTeam error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


}
